#include "deviceinfo.h"
#include "ui_deviceinfo.h"
#include "timeutils.h"
#include "crc32verifier.h"
#include "broadthread.h"
#include "tcpDepthWorker.h"
#include "tcpProtocolWorker.h"
#include "ftpclient.h"
#include "rgbcapture.h"
#include "singleton.h"
#include "tcpIrWorker.h"
#include "depthClouddataprocessor.h"

#include <QtEndian>
#include <QTimer>
#include <QFileDialog>
#include <QMessageBox>
#include <QtConcurrent>


// 端口号大小端转换
quint16 convertLittleEndianToPort(const QByteArray& data)
{
    if (data.size() != 2) {
        qWarning() << "数据长度错误，应为2个字节";
        return 0;
    }

    // 使用 Qt 的 fromLittleEndian 函数直接转换
    return static_cast<quint16>(qFromLittleEndian<quint16>(reinterpret_cast<const uchar*>(data.data())));
}

/**
 * 将16进制字符串温度值转换为实际温度
 * @param hexTempStr 16进制温度字符串，格式如"A80C"
 * @param swapBytes 是否需要交换字节顺序
 * @param divisor 转换因子，默认为100
 * @return 转换后的实际温度值，如果转换失败返回NaN
 */
double convertHexToTemperature(const QString& hexTempStr, bool swapBytes = true, double divisor = 100.0)
{
    QString processedStr = hexTempStr;
    // 如果需要交换字节顺序
    if (swapBytes && processedStr.length() == 4) {
        processedStr = processedStr.mid(2, 2) + processedStr.mid(0, 2);
    }
    // 将16进制字符串转换为十进制整数
    bool ok;
    int tempValue = processedStr.toInt(&ok, 16);
    if (ok) {
        // 计算实际温度
        return tempValue / divisor;
    }
    else {
        // 转换失败，返回NaN
        return qQNaN();
    }
}
DeviceInfo::DeviceInfo(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DeviceInfo),uploadFileType(Upgrade), m_ftpClient(FTPClientInstance), downLoadType(0)
{
    ui->setupUi(this);
    m_timer = new QTimer(this);
    m_timer->setInterval(1000);
    m_timerConnectDepth = new QTimer(this);
    m_timerConnectDepth->setInterval(4000);
    connect(m_timer, &QTimer::timeout, this, &DeviceInfo::sendHeartBeat);
    connect(m_timerConnectDepth, &QTimer::timeout, this, &DeviceInfo::buildConnectDepth);
    //m_timerConnectDepth->start();
    
    //m_ftpManager = new FtpManager(this);
    //connect(m_ftpManager, &FtpManager::uploadFinished, this, &DeviceInfo::onUploadFinished);


    qDebug() << "DeviceInfo" << QThread::currentThreadId();
    broadThread = new BroadThread();
    broadThread->setPort(2025);
    connect(broadThread, &BroadThread::datagramReceived, this, &DeviceInfo::onTcpDataReceived);
    broadThread->start();  // 延迟执行线程启动


    depthThread = new QThread();
    tcpDepthWorker = TcpDepthWorkerInstance;
    tcpDepthWorker->moveToThread(depthThread);
    connect(tcpDepthWorker, &TcpDepthWorker::disconnected, this, &DeviceInfo::onTcpDisconnected);
    depthThread->start();

    connect(tcpDepthWorker, &TcpDepthWorker::stopConnectDepthTimer, this, &DeviceInfo::stopDepthTimer);

    irThread = new QThread();
    tcpIrWorker = TcpIrWorkerInstance;
    tcpIrWorker->moveToThread(irThread);
    irThread->start();

    protocolThread = new QThread();
    tcpProtocolWorker = TcpProtocolWorkerInstance;
    tcpProtocolWorker->moveToThread(protocolThread);
    protocolThread->start();
    connect(tcpProtocolWorker, &TcpProtocolWorker::connected, this, &DeviceInfo::onTcpConnected);
    connect(this, &DeviceInfo::sendTcpData, tcpProtocolWorker, &TcpProtocolWorker::sendData, Qt::QueuedConnection);
    connect(tcpProtocolWorker, &TcpProtocolWorker::readyReadData, this, &DeviceInfo::onTcpDataReceived);

    connect(this, &DeviceInfo::sendDepthAndIRDisConnectSignal, tcpDepthWorker, &TcpDepthWorker::onDisconnectSocket);
    connect(this, &DeviceInfo::sendDepthAndIRDisConnectSignal, tcpIrWorker, &TcpIrWorker::onDisconnectSocket);


    depthCloudDataProcessor = DepthCloudDataProcessorInstance;
    connect(this, &DeviceInfo::sendInitGeneral, depthCloudDataProcessor, &DepthCloudDataProcessor::onRecvInitGeneral);

    connect(ui->tabWidget, &QTabWidget::currentChanged, this, &DeviceInfo::onTabChanged);

    connect(m_ftpClient, &FTPClient::directoryListingReady,
            this, &DeviceInfo::onDirectoryListingReady);
    connect(m_ftpClient, &FTPClient::directoryListingError,
            this, &DeviceInfo::onDirectoryListingError);

    connect(&m_downloadWatcher, &QFutureWatcher<bool>::finished,
            this, &DeviceInfo::onDownloadFinshed);
    connect(m_ftpClient, &FTPClient::downloadProgress,
            this, &DeviceInfo::onDownloadProgress);


    connect(m_ftpClient, &FTPClient::uploadProgress, this, &DeviceInfo::onUploadProgress);
    connect(m_ftpClient, &FTPClient::uploadFinished, this, &DeviceInfo::onUploadFinished);
    connect(m_ftpClient, &FTPClient::uploadError, this, &DeviceInfo::onUploadError); 

    ui->listWidget->setSelectionMode(QAbstractItemView::MultiSelection);

    ui->tabWidget->setCurrentIndex(0);
}

DeviceInfo::~DeviceInfo()
{

    if (broadThread != nullptr && broadThread->isRunning())
    {
        broadThread->requestInterruption();
        broadThread->quit();
        broadThread->wait();
        delete broadThread;
        broadThread = nullptr;
    }
    if (depthThread != nullptr && depthThread->isRunning())
    {
        depthThread->requestInterruption();
        depthThread->quit();
        depthThread->wait();
        delete depthThread;
        depthThread = nullptr;
    }
    if (irThread != nullptr && irThread->isRunning())
    {
        irThread->requestInterruption();
        irThread->quit();
        irThread->wait();
        delete irThread;
        irThread = nullptr;
    }
    if (protocolThread != nullptr && protocolThread->isRunning())
    {
        protocolThread->requestInterruption();
        protocolThread->quit();
        protocolThread->wait();
        delete protocolThread;
        protocolThread = nullptr;
    }
    delete ui;
}

QString DeviceInfo::getFtpUrl() const
{
    return ui->UrlEdit->text();
}

QString DeviceInfo::getFtpUsername() const
{
    return ui->UserEdit->text();
}

QString DeviceInfo::getFtpPassword() const
{
    return ui->passEdit->text();
}

QString DeviceInfo::getFtpRemoteDir() const
{
    return QString();
}

void DeviceInfo::on_SearchDeviceBtn_clicked()
{
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    //19051D0917210100000000000000000000000100010000000000
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    QByteArray hexTime = binaryTime.toHex().toUpper();
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0400010000000000");
    //qDebug() << "fullFrame" << partFrame.toHex(' ').toUpper();
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    // AA55AA55AA55AA550000000000011907190A20210100000000000000000000000400010000000000010203040506070827E93B59EEFFEEFF
    qDebug() << "fullFrame" << fullFrame.toHex().toUpper();
    emit sendTcpData(fullFrame);
}

void DeviceInfo::on_SetIPBtn_clicked()
{
    QMessageBox::information(this, "提示", "此操作,雷达系统需要重新启动，大约需要20秒");
    QString ipStr = ui->ipSetEdit->text().trimmed();
    QByteArray ipData = TimeUtils::ipStringToByteArray(ipStr);
    qDebug() << "ipData" << ipData.toHex();


    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    //QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0800010000000000");
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("08") + ipData + QByteArray::fromHex("000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    qDebug() << "fullFrame" << fullFrame.toHex().toUpper();
    emit sendTcpData(fullFrame);
}


void DeviceInfo::on_restartBtn_clicked()
{
    QMessageBox::information(this, "提示", "此操作雷达系统需要重启，可能需要20秒");
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0700010000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    //qDebug() << "111111111111111111111" << fullFrame.toHex().toUpper();
    emit sendTcpData(fullFrame);
    // 断开深度图和IR图信号
    emit sendDepthAndIRDisConnectSignal();
}


void DeviceInfo::on_syncTimeBtn_clicked()
{
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    qDebug() << "binaryTime" << binaryTime.toHex().toUpper();
    //QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("03000100000000000000000000000000");
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("030001")+ binaryTime + QByteArray::fromHex("00000000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    qDebug() << "fullFrame" << fullFrame.toHex();
    emit sendTcpData(fullFrame);
}

void DeviceInfo::handleBroadcastMessage(const QByteArray& data, const QHostAddress& address)
{
    qDebug() << "数据文本：" << QString::fromUtf8(data);
    // 广播地址
    qDebug() << "收到广播来自：" << address.toString();
    QByteArray hexArr = data.toHex().toUpper();
    // AA 55 AA 55 AA 55 AA 55 01 00 00 00 00 01 19 06 03 0E 08 1D 01 00 00 00 00 00 00 00 00 00 00 00 01 01 01 02 03 04 D1 07 00 00 00 00 00 00 00 00 01 02 03 04 05 06 07 08 63 1B 42 6B EE FF EE FF
    qDebug() << "数据 Hex：" << hexArr;
    QByteArray fullFrame = QByteArray::fromHex(hexArr);
    if (!CRC32Verifier::verify(fullFrame))
    {
        qDebug() << "CRC32校验失败";
        return;
    }
    // 校验通过
    if (hexArr.mid(20, 8) == "00000001")
    {
        qDebug() << "北京时间";
    }
    // 广播时间
    qDebug() << hexArr.mid(28, 12);
    QByteArray dataTime = QByteArray::fromHex(hexArr.mid(28, 12));
    QString time = TimeUtils::parseHexToDateTimeString(dataTime);
    qDebug() << time;

    // 广播产品类型
    if (hexArr.mid(40, 2) == "01")
    {
        qDebug() << "TH-S01";
    }
    // 心跳包里面的类型
    if (hexArr.mid(64, 2) == "01")
    {
        qDebug() << "TH-S01–SMT010101";
    }
    if (hexArr.mid(66, 2) == "01")
    {
        qDebug() << "空闲";
    }
    QString ipStr = TimeUtils::hexToIp(hexArr.mid(68, 8));
    qDebug() << "IP地址：" << ipStr;
    quint16 port = convertLittleEndianToPort(QByteArray::fromHex(hexArr.mid(76, 4)));
    qDebug() << port;
    

    QMetaObject::invokeMethod(tcpProtocolWorker, "connectToServer", Qt::QueuedConnection,
       Q_ARG(QString, ipStr),
       Q_ARG(quint16, port));
    // 设置UI
    ui->ipEdit->setText(ipStr);
    ui->portEdit->setText(QString::number(port));
    ui->ipSetEdit->setText(ipStr);
    this->m_port = port;
    if (this->m_ipStr != ipStr)
    {
        this->m_ipStr = ipStr;
        emit sendRtspIpAddress("rtsp://" + ipStr + ":" + QString::number(8554) + "/unicast");
    }

    ui->UrlEdit->setText("ftp://" + ipStr);
    protocolThread->start(); // 启动线程
}



void DeviceInfo::handleTimeSyncMessage(const QByteArray& message)
{
    // 帧头32Byte
    QByteArray hexArr = message.toHex().toUpper();
    qDebug() << "hexArr" << hexArr;
    qDebug() << "hexArr" << hexArr.mid(64, 2);
    // 确认收到
    qDebug() << "hexArr" << hexArr.mid(66, 4);
    // 时区
    qDebug() << "hexArr" << hexArr.mid(70, 4);
    // 时间
    qDebug() << "hexArr" << hexArr.mid(74, 12);
    ui->timeLabel->setText(TimeUtils::parseHexToDateTimeString(QByteArray::fromHex(hexArr.mid(74, 12))));

    
}

void DeviceInfo::handleDeviceInfoMessage(const QByteArray &message)
{
    // 帧头32Byte
    QByteArray hexArr = message.toHex().toUpper();
    qDebug() << "hexArr" << hexArr;
    //AA55AA55AA55AA55018100000001190606112C0101000000000000000000000004C0A80010000000000000000000000000000000000000B90B7800640001000100000100010001FFFFFFFFFFFF0100190606112C01110000002200000000000000053300000044000000550000006600770088009900FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000065D3F4F0CC1A8FFFFFFFFFFFFFFFF48A5CE34EEFFEEFF
    QByteArray dataTime = QByteArray::fromHex(hexArr.mid(28, 12));
    QString time = TimeUtils::parseHexToDateTimeString(dataTime);
    qDebug() << "time" << time;
    if (hexArr.mid(40, 2) == "01")
    {
        ui->DeviceTypeLab->setText("设备类型:TH-S01");
    }
    if (hexArr.mid(64, 2) == "04")
    {
        qDebug() << "data Type 04";
    }
    qDebug() << hexArr.mid(66, 8);
    QString ipStr = TimeUtils::hexToIp(hexArr.mid(66, 8));
    qDebug() << "ip" << ipStr;
    ui->ipLab->setText("ip:" + ipStr);
    ui->ipEdit->setText(ipStr);
    qDebug() << hexArr.mid(110, 4);
    quint16 port = TimeUtils::convertLittleEndianToPort(QByteArray::fromHex(hexArr.mid(110, 4)));
    qDebug() << port;
    ui->portLab->setText("端口号:" + QString::number(port));
    ui->portEdit->setText(QString::number(port));

    QByteArray fov = hexArr.mid(114, 8);
    qDebug()<<"FOV" << fov;
    //ui->fovLab->setText("FOV:" + fov);
    // 下位机软件版本号
    QByteArray ESW_Version = hexArr.mid(122, 10);
    qDebug() << "ESW_Version" << ESW_Version;
    ui->ESWLab->setText("软件版本号:" + ESW_Version);
    // 下位机硬件版本号
    QByteArray HW_Version = hexArr.mid(132, 10);
    qDebug() << "HW_Version" << HW_Version;
    ui->HWLab->setText("硬件版本号:" + HW_Version);
    // 下位机的SN号
    QByteArray SN = hexArr.mid(142, 12);
    qDebug() << "SN" << SN;
    //ui->SNLab->setText("SN:" + SN);
    // 下位机的时间
    QByteArray lowerTime = hexArr.mid(154, 16);
    qDebug() << "lowerTime" << lowerTime;
    QString lowertime = TimeUtils::parseHexToDateTimeString(QByteArray::fromHex(hexArr.mid(158, 12)));
    qDebug() << "lowertime" << lowertime;
    //产品总运行时间
    QByteArray TotalRunTime = hexArr.mid(170, 8);
    qDebug() << "TotalRunTime" << TotalRunTime;
    //ui->TotalRunLab->setText("运行时间:" + TotalRunTime);
    //产品运行次数
    QByteArray OperationsTimeCount = hexArr.mid(178, 16);
    qDebug() << "OperationsTimeCount" << OperationsTimeCount;
    //ui->OperationCount->setText("运行次数:" + OperationsTimeCount);
    // 诊断信息
    QByteArray FaultDiagnosis = hexArr.mid(194, 64);
    qDebug() << "FaultDiagnosis" << FaultDiagnosis;
    // 数据类型
    QByteArray DataType = hexArr.mid(194, 2);
    qDebug() << "DataType" << DataType;
    // 电压
    QString voltageStr = hexArr.mid(196, 8);
    double voltage = TimeUtils::hexToVoltage(voltageStr);
    qDebug() << "voltage" << voltage;
    //ui->voltageLab->setText("电压:" + QString::number(voltage));
    // 电流
    QString electricStr = hexArr.mid(204, 8);
    qDebug() << "electricStr" << electricStr;
    double electric = TimeUtils::hexToVoltage(electricStr);
    qDebug() << "electric" << electric;
    //ui->electricLab->setText("电流:" + QString::number(electric));
    // 功耗
    QString consumptionStr = hexArr.mid(212, 8);
    qDebug() << "consumptionStr" << consumptionStr;
    double consumption = TimeUtils::hexToVoltage(consumptionStr);
    qDebug() << "consumption" << consumption;
    //ui->consumptionLab->setText("功耗:" + QString::number(consumption));
    
    // #1发射器温度
    QString Transmitter01TempStr = hexArr.mid(220, 4);
    qDebug() << "原始温度值:" << Transmitter01TempStr;  // 输出: A80C
    // 调用转换函数
    double Temp01 = convertHexToTemperature(Transmitter01TempStr);
    ui->emitter1Lab->setText("#1发射器温度:" + QString::number(Temp01));

    // #2发射器温度
    QString Transmitter02TempStr = hexArr.mid(224, 4);
    qDebug() << "TransmitterTemp" << Transmitter02TempStr;
    double Temp02 = convertHexToTemperature(Transmitter02TempStr);
    ui->emitter2Lab->setText("#2发射器温度:" + QString::number(Temp02));

    // #3发射器温度
    QString Transmitter03TempStr = hexArr.mid(228, 4);
    qDebug() << "TransmitterTemp" << Transmitter03TempStr;
    double Temp03 = convertHexToTemperature(Transmitter03TempStr);
    ui->emitter3Lab->setText("#3发射器温度:" + QString::number(Temp03));

    // #4发射器温度
    QString Transmitter04TempStr = hexArr.mid(232, 4);
    qDebug() << "TransmitterTemp" << Transmitter04TempStr;
    double Temp04 = convertHexToTemperature(Transmitter04TempStr);
    ui->emitter4Lab->setText("#4发射器温度:" + QString::number(Temp04));

    // 接收器温度
    QString ReceiverTempStr = hexArr.mid(236, 4);
    double ReceiverTemp = convertHexToTemperature(ReceiverTempStr);
    ui->receiverLab->setText("接收器温度:" + QString::number(ReceiverTemp));

    // SOC温度
    QString SOCTempStr = hexArr.mid(240, 4);
    qDebug() << "SOCTempStr" << SOCTempStr;
    double SOCTemp = convertHexToTemperature(SOCTempStr);
    ui->SOCLab->setText("SOC温度:" + QString::number(SOCTemp));

    // PCB温度
    QString PCBTempStr = hexArr.mid(244, 4);
    double PCBTemp = convertHexToTemperature(PCBTempStr);
    //ui->PCBLab->setText("设备温度:" + QString::number(PCBTemp));




    
}

void DeviceInfo::handleDiagnosticsMessage(const QByteArray &message)
{

}
// 处理升级指令
void DeviceInfo::handleUpgradeStatusMessage(const QByteArray& message)
{
    QByteArray hexArr = message.toHex().toUpper();
    qDebug() << "handleRebootCommand" << hexArr;
    // 数据类型
    qDebug() << "handleRebootCommand" << hexArr.mid(64, 2);
    // 状态 00 空闲 01 正在升级  02 升级完成
    qDebug() << "handleRebootCommand" << hexArr.mid(66, 2);
    if (hexArr.mid(66, 2) == "02")
    {
        QMessageBox::information(this, "升级完成", "升级完成");
        qDebug() << "升级完成";
    }
    else if (hexArr.mid(66, 2) == "03")
    {
        QMessageBox::information(this, "升级失败", "升级失败");
        qDebug() << "升级失败";
    }
    // 升级进度 0%代表空闲 100%代表升级完成
    qDebug() << "handleRebootCommand" << hexArr.mid(68, 2);
    // 预留扩展
    qDebug() << "handleRebootCommand" << hexArr.mid(70, 10);
    
}

void DeviceInfo::sendHeartBeat()
{
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0200010000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    emit sendTcpData(fullFrame);
}


void DeviceInfo::onTcpDataReceived(const QByteArray& mess, const QHostAddress& address)
{
    if (mess.size() < 32) {
        qDebug() << "无效的消息长度";
        return;
    }
    QByteArray hexArr = mess.toHex().toUpper();
    //qDebug() << "数据 Hex：" << hexArr;
    QByteArray fullFrame = QByteArray::fromHex(hexArr);
    if (!CRC32Verifier::verify(fullFrame))
    {
        qDebug() << "校验失败";
        return;
    }
    quint8 dataType = static_cast<quint8>(mess[32]);
    // 使用 switch 区分不同的数据类型
    switch (dataType)
    {
    case 0x01:
        handleBroadcastMessage(mess, address); // 广播
        break;

    case 0x02:
        handleHeartbeatMessage(mess); // 心跳
        break;

    case 0x03:
        handleTimeSyncMessage(mess); // 授时
        break;

    case 0x04:
        handleDeviceInfoMessage(mess); // 设备信息
        break;

    case 0x05:
        handleDiagnosticsMessage(mess); // 诊断信息
        break;

    case 0x06:
        handleUpgradeStatusMessage(mess); // 升级状态
        break;

    case 0x07:
        handleRebootCommand(mess); // 重启命令
        break;

    case 0x08:
        handleSetIpMessage(mess); // 设置IP
        break;

    case 0x09:
        handleConfigurationRegisterMessage(mess); // 配置sensor寄存器
        break;
    case 0x0A:
        handleGetDepthInfoMessage(mess); // 配置sensor寄存器
        break;
    default:
        qDebug() << "未知的数据类型：" << QString("0x%1").arg(dataType, 2, 16, QChar('0')).toUpper();
        break;
    }
}

// 心跳消息处理
void DeviceInfo::handleHeartbeatMessage(const QByteArray& message)
{
    QByteArray hexArr = message.toHex().toUpper();
    // AA55AA55AA55AA55010800000001190606100835010000000000000000000000020100FFFFFFFFFFFFFFFFFFFFFFFFFFA3FE1E6FEEFFEEFF
    QByteArray dataTime = QByteArray::fromHex(hexArr.mid(28, 12));
    QString time = TimeUtils::parseHexToDateTimeString(dataTime);
    ui->timeLabel->setText(time);
    //qDebug() << time;
    // 广播产品类型
    if (hexArr.mid(40, 2) == "01")
    {
        qDebug() << "TH-S01";
    }
    if (hexArr.mid(64, 2) == "02")
    {
        qDebug() << "data type 02";
    }
    if (hexArr.mid(66, 4) == "0000")
    {
        qDebug() << "空闲";
    }

    
}
void DeviceInfo::on_ipConnectBtn_clicked()
{
    QString ipStr = ui->ipEdit->text();
    quint16 port = ui->portEdit->text().toUShort();
    QMetaObject::invokeMethod(tcpDepthWorker, "connectToServer", Qt::QueuedConnection,
        Q_ARG(QString, ipStr),
        Q_ARG(quint16, port));
    depthThread->start(); // 启动线程

    QMetaObject::invokeMethod(tcpIrWorker, "connectToServer", Qt::QueuedConnection,
        Q_ARG(QString, this->m_ipStr),
        Q_ARG(quint16, 4002));
    if (!irThread->isRunning())
    {
        irThread->start(); // 启动线程
    }


}

void DeviceInfo::handleRebootCommand(const QByteArray& message)
{
    QByteArray hexArr = message.toHex().toUpper();
    qDebug() << "handleRebootCommand" << hexArr;
    qDebug() << "handleRebootCommand" << hexArr.mid(64, 2);
    qDebug() << "handleRebootCommand" << hexArr.mid(66, 4);
    qDebug() << "handleRebootCommand" << hexArr.mid(70, 10);
    
}

void DeviceInfo::handleSetIpMessage(const QByteArray& message)
{
    QByteArray hexArr = message.toHex().toUpper();
    qDebug() << "handleRebootCommand" << hexArr;
    qDebug() << "handleRebootCommand" << hexArr.mid(64, 2);
    qDebug() << "handleRebootCommand" << hexArr.mid(66, 4);
    qDebug() << "handleRebootCommand" << hexArr.mid(70, 10);
}

void DeviceInfo::handleConfigurationRegisterMessage(const QByteArray& message)
{
    QByteArray hexArr = message.toHex().toUpper();
    qDebug() << "handleRebootCommand" << hexArr;
    // 数据类型
    qDebug() << "handleRebootCommand" << hexArr.mid(64, 2);
    // 配置寄存器成功或者失败
    qDebug() << "handleRebootCommand" << hexArr.mid(64, 4);
    if (hexArr.mid(64, 4) == "0901")
    {
        qDebug() << "寄存器配置成功";
        QMessageBox::information(nullptr, "提示", "开始配置eeprom");
    }
    if (hexArr.mid(64, 4) == "0902")
    {
        qDebug() << "寄存器配置成功";
        QMessageBox::information(nullptr, "提示", "eeprom写入成功，请重启设备");
    }
    // 预留扩展
    qDebug() << "handleRebootCommand" << hexArr.mid(70, 10);
}

void DeviceInfo::handleGetDepthInfoMessage(const QByteArray& message)
{
    qDebug() << "111111111111"<< message;
}



// 下发升级指令
void DeviceInfo::on_gradeStatusBtn_clicked()
{
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0600010000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    emit sendTcpData(fullFrame);
}

void DeviceInfo::onTcpConnected()
{
    // 这个是发送获取设备信息的指令onTabChanged(0);
    onTabChanged(0);
    qDebug() << "已连接TCP";
    QMessageBox::information(nullptr, "提示", "协议已建立连接");
    //m_timer->start();
    //QTimer::singleShot(2000, this, &DeviceInfo::sendGetDepthCommand);
    // 获取yaml文件
    downLoadAllNodeYaml();

}

void DeviceInfo::onTcpDisconnected()
{
    qDebug() << "已断开TCP";
    //QMessageBox::information(this, "提示", "断开连接");
}

void DeviceInfo::onTabChanged(int index)
{
    qDebug() << "Tab Changed to:" << index;
    if (index == 0)
    {
        QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
        //19051D0917210100000000000000000000000100010000000000
        QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
        QByteArray hexTime = binaryTime.toHex().toUpper();
        QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0400010000000000");
        //qDebug() << "fullFrame" << partFrame.toHex(' ').toUpper();
        quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
        QByteArray crcBytes;
        crcBytes.resize(4);
        qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
        QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
        qDebug() << "fullFrame" << fullFrame.toHex(' ').toUpper();
        emit sendTcpData(fullFrame);
    }
}




void DeviceInfo::upLoadUpFileSwitch(UploadFileInfo type)
{
    QString ftpServer = ui->UrlEdit->text();
    QString user = ui->UserEdit->text();
    QString pwd = ui->passEdit->text();

    QString localPath;
    QString filter;

    // 根据类型选择不同的文件过滤器
    switch (type) {
    case 0:
        // 只允许选择ZIP文件
        filter = "ZIP文件 (*.zip)";
        break;
    case 1:
        // 只允许选择INI文件
        filter = "配置文件 (*.ini)";
        break;
    default:
        // 默认允许选择所有文件
        filter = "所有文件 (*)";
        break;
    }

    // 打开文件选择对话框
    localPath = QFileDialog::getOpenFileName(
        this, "选择要上传的文件", "", filter
        );

    if (!localPath.isEmpty()) {
        QFileInfo fileInfo(localPath);

        QString fileName = fileInfo.fileName();
        if (fileInfo.suffix().compare("ini", Qt::CaseInsensitive) == 0)
        {
            if (fileName != "reg.ini") {
                fileName = "reg.ini";
            }
        }
        else if (fileInfo.suffix().compare("zip", Qt::CaseInsensitive) == 0)
        {
            if (fileName != "upgrade_package.zip") {
                fileName = "upgrade_package.zip";
            }
        }
        QString remotePath = "uploads/" + fileName;

        // 重置进度条
        ui->progressBar->setRange(0, 100);
        ui->progressBar->setValue(0);
        ui->progressBar->show();
        ui->upgradeBtn->setEnabled(false);

        // 开始上传
        //m_ftpManager->uploadFile(ftpServer, user, pwd, localPath, remotePath, ui->progressBar);
        QFuture<bool> future = m_ftpClient->uploadFileAsync(
            ftpServer, user, pwd, localPath, remotePath
        );
        manageUploadTask(future, fileInfo.fileName());
    }
}


void DeviceInfo::on_upgradeBtn_clicked()
{
    upLoadUpFileSwitch(Upgrade);
    uploadFileType = Upgrade;
}

void DeviceInfo::on_ConfigurationRegisterBtn_clicked()
{
    upLoadUpFileSwitch(ConfigurationRegister);
    uploadFileType = ConfigurationRegister;
}

void DeviceInfo::on_getDire_clicked()
{
    QString ftpUrl = ui->UrlEdit->text();
    QString username = ui->UserEdit->text();
    QString password = ui->passEdit->text();

    QString remoteDir = ui->remoteDirEdit->text();
    if (remoteDir.isEmpty()) {
        remoteDir = "/";  // 默认查看根目录
    }

    ui->listWidget->clear();  // 清空现有列表
    // 启动异步目录列表获取任务
    QFuture<QStringList> future = m_ftpClient->getDirectoryListingAsync(
        ftpUrl, username, password, remoteDir
        );
    m_directoryWatcher.setFuture(future);

    // 禁用按钮，避免重复点击
    ui->getDire->setEnabled(false);
}

void DeviceInfo::onDirectoryListingReady(const QStringList &files)
{
    ui->listWidget->clear();

    if (files.isEmpty()) {
        ui->listWidget->addItem("目录为空或无法访问");
    } else {
        for (const QString &file : files) {
            ui->listWidget->addItem(file);
        }
    }

    ui->statusLabel->setText(QString("找到 %1 个文件/目录").arg(files.size()));
    ui->getDire->setEnabled(true);
}

void DeviceInfo::onDirectoryListingError(const QString &errorMessage)
{
    ui->listWidget->clear();
    ui->listWidget->addItem("获取目录列表失败: " + errorMessage);
    ui->statusLabel->setText("获取目录列表失败");
    ui->getDire->setEnabled(true);
}


void DeviceInfo::on_batchDownloadButton_clicked()
{
    QList<QListWidgetItem*> selectedItems = ui->listWidget->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要下载的文件");
        return;
    }
    // 批量下载
    downLoadType = 1;
    QString ftpUrl = ui->UrlEdit->text();
    QString username = ui->UserEdit->text();
    QString password = ui->passEdit->text();
    QString remoteDir = ui->remoteDirEdit->text();
    if (remoteDir.isEmpty()) remoteDir = "/";

    // 创建存储文件夹
    //QString appDirPath = QApplication::applicationDirPath();
    //QString storageFolder = appDirPath + "/remoteFileLog";
    //QDir().mkpath(storageFolder);

    QString appDirPath = QApplication::applicationDirPath();
    QDir dir(appDirPath);
    QString storageFolder;
    if (dir.cdUp())
    {
        storageFolder = dir.absolutePath() + "/remoteFileLog";
    }
    QDir().mkpath(storageFolder);

    QList<QFuture<bool>> downloadFutures;
    for (QListWidgetItem* item : selectedItems) {
        QString remoteFile = item->text();
        // 清理文件名
        remoteFile = remoteFile.trimmed();
        remoteFile = remoteFile.replace("\r", "");
        remoteFile = remoteFile.replace("\n", "");
        remoteFile = remoteFile.replace("/", "_");
        remoteFile = remoteFile.replace("\\", "_");
        if (remoteFile.endsWith('/') || remoteFile.endsWith('\\')) continue;  // 跳过目录

        QString fullRemotePath = remoteDir + "/" + remoteFile;
        QString localFileName = remoteFile;
        QString localPath = storageFolder + "/" + localFileName;

        QFuture<bool> future = m_ftpClient->downloadFileAsync(
            ftpUrl, username, password, fullRemotePath, localPath
            );
        downloadFutures.append(future);
    }

    if (!downloadFutures.isEmpty()) {
        manageBatchDownload(downloadFutures);
    }
}

void DeviceInfo::onDownloadFinshed()
{
    bool success = m_downloadWatcher.result();
    // ui->downloadButton->setEnabled(true);

    if (success) {
        QMessageBox::information(this, "成功", "文件下载完成！");
        ui->statusLabel->setText("下载完成");
    } else {
        QMessageBox::critical(this, "失败", "文件下载失败，请检查日志！");
        ui->statusLabel->setText("下载失败");
    }
}

void DeviceInfo::onDownloadProgress(const QString &fileName, int progress)
{
    ui->ftpProgressBar->setValue(progress);
    ui->statusLabel->setText(QString("%1 - 下载进度：%2%").arg(fileName).arg(progress));
}
void DeviceInfo::manageBatchDownload(const QList<QFuture<bool>> &futures)
{
    ui->ftpProgressBar->setValue(0);
    ui->statusLabel->setText("开始批量下载...");
    ui->batchDownloadButton->setEnabled(false);

    int totalTasks = futures.size();
    QAtomicInt* completedTasks = new QAtomicInt(1);

    QString exeDir = QCoreApplication::applicationDirPath();
    QString yamlFilePath = exeDir + "/all_node.yaml";

    for (const QFuture<bool> &future : futures) {
        QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>(this);
        watcher->setFuture(future);

        connect(watcher, &QFutureWatcher<bool>::finished, [this, watcher, totalTasks, completedTasks, yamlFilePath]() {
            int completed = completedTasks->fetchAndAddRelaxed(1);
            int progress = (completed * 100) / totalTasks;
            ui->ftpProgressBar->setValue(progress);
            ui->statusLabel->setText(QString("批量下载：%1/%2 (%3%)").arg(completed).arg(totalTasks).arg(progress));
            // 单独下载yaml文件到exe
            if (downLoadType == 0)
            {
                QFuture<bool> fileCheckFuture = checkFileAsync(yamlFilePath);
                QFutureWatcher<bool>* fileWatcher = new QFutureWatcher<bool>(this);
                connect(fileWatcher, &QFutureWatcher<bool>::finished, [this, fileWatcher]() {
                    bool fileValid = fileWatcher->result();
                    if (fileValid)
                    {
                        QMessageBox::information(this, "成功", "配置文件下载完成！约10秒将自动开启点云!");
                        emit sendInitGeneral();
                        m_timer->start();
                        m_timerConnectDepth->start();
                        QTimer::singleShot(1500, this, &DeviceInfo::sendGetDepthCommand);
                    }
                    else {
                        QMessageBox::warning(this, "错误", "配置文件为空或下载失败，请重新下载！");
                    }
                    fileWatcher->deleteLater();
                    });
                fileWatcher->setFuture(fileCheckFuture);
                ui->batchDownloadButton->setEnabled(true);
            }
            else 
            {
                if (completed == totalTasks) {
                    ui->statusLabel->setText("批量下载完成");
                    ui->batchDownloadButton->setEnabled(true);
                    QMessageBox::information(this, "成功", "所有文件下载完成！");
                }
            }
            
        });

        connect(watcher, &QFutureWatcher<bool>::finished, watcher, &QObject::deleteLater);
    }
}

void DeviceInfo::on_uploadButton_clicked()
{
    QString localFile = QFileDialog::getOpenFileName(this, "选择要上传的文件");
    if (localFile.isEmpty()) return;

    QString ftpUrl = ui->UrlEdit->text();
    QString username = ui->UserEdit->text();
    QString password = ui->passEdit->text();
    QString remoteDir = ui->remoteDirEdit->text();
    if (remoteDir.isEmpty()) remoteDir = "/";

    QFileInfo fileInfo(localFile);
    QString remoteFile = remoteDir + "/" + fileInfo.fileName();

    ui->statusLabel->setText("准备上传: " + fileInfo.fileName());
    ui->uploadButton->setEnabled(false);
    ui->progressBar->setValue(0);

    QFuture<bool> future = m_ftpClient->uploadFileAsync(
        ftpUrl, username, password, localFile, remoteFile
        );

    manageUploadTask(future, fileInfo.fileName());
}

void DeviceInfo::onUploadProgress(const QString &fileName, int progress)
{
    ui->progressBar->setValue(progress);
    ui->statusLabel->setText(QString("上传进度: %1 - %2%").arg(fileName).arg(progress));
}

void DeviceInfo::onUploadFinished(const QString &fileName, bool success)
{
    if (success) {
        switch (uploadFileType) {
            // 升级
        case Upgrade:
        {
            QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
            QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
            QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0600010000000000");
            quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
            QByteArray crcBytes;
            crcBytes.resize(4);
            qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
            QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
            emit sendTcpData(fullFrame);
        }
        break;
        // 配置寄存器
        case ConfigurationRegister:
        {
            QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
            QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
            QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0900010000000000");
            quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
            QByteArray crcBytes;
            crcBytes.resize(4);
            qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
            QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
            //qDebug() << "fullFrame" << fullFrame.toHex().toUpper();
            //AA55AA55AA55AA550000000000011907120B072F010000000000000000000000090001000000000001020304050607089305F1F9EEFFEEFF
            emit sendTcpData(fullFrame);
        }
        break;
        default:
            break;
        }
        //QMessageBox::information(this, "成功", "文件上传完成");
    }
    else {
        ui->statusLabel->setText("文件上传失败: " + fileName);
    }
}

void DeviceInfo::onUploadError(const QString &fileName, const QString &errorMessage)
{
    ui->statusLabel->setText("上传错误: " + fileName + " - " + errorMessage);
    QMessageBox::warning(this, "上传错误", errorMessage);
}

void DeviceInfo::sendGetDepthCommand()
{
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0A00010000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    emit sendTcpData(fullFrame);
    qDebug() << "111111111" << fullFrame.toHex().toUpper();
    m_timerConnectDepth->start();
    QTimer::singleShot(6500, this, &DeviceInfo::buildConnectDepth);
}

void DeviceInfo::buildConnectDepth()
{
    QMetaObject::invokeMethod(tcpDepthWorker, "connectToServer", Qt::QueuedConnection,
        Q_ARG(QString, this->m_ipStr),
        Q_ARG(quint16, 4001));


    QMetaObject::invokeMethod(tcpIrWorker, "connectToServer", Qt::QueuedConnection,
        Q_ARG(QString, this->m_ipStr),
        Q_ARG(quint16, 4002));
}

void DeviceInfo::stopDepthTimer()
{
    m_timerConnectDepth->stop();
}

void DeviceInfo::downLoadAllNodeYaml()
{
    QString ftpUrl = ui->UrlEdit->text();
    QString username = ui->UserEdit->text();
    QString password = ui->passEdit->text();

    // 构建远程文件路径：uploads/all_node.yaml
    QString remoteDir = "/uploads";
    QString remoteFile = "all_node.yaml";
    QString fullRemotePath = remoteDir + "/" + remoteFile;

    // 直接使用exe所在目录作为存储路径
    QString localPath = QApplication::applicationDirPath() + "/" + remoteFile;

    // 检查FTP信息是否完整
    if (ftpUrl.isEmpty() || username.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先设置FTP连接信息");
        return;
    }

    // 显示下载提示
    QMessageBox::information(this, "提示", "开始下载配置文件...");

    // 异步下载文件
    QFuture<bool> future = m_ftpClient->downloadFileAsync(
        ftpUrl, username, password, fullRemotePath, localPath
    );
    downLoadType = 0;
    // 管理下载结果
    QList<QFuture<bool>> downloadFutures;
    downloadFutures.append(future);
    manageBatchDownload(downloadFutures);

}

void DeviceInfo::startPointCloudSlot()
{
    emit startPointCloudSignal(true);
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    qDebug() << "binaryTime" << binaryTime.toHex().toUpper();
    //QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("03000100000000000000000000000000");
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0A0001") + binaryTime + QByteArray::fromHex("0000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    qDebug() << "fullFrame" << fullFrame.toHex();
    if (m_timer->isActive())
    {
        m_timer->stop();
    }
    emit sendTcpData(fullFrame);
}

void DeviceInfo::onRectReStartCommand()
{
    qDebug() << "111";
    QByteArray dataPart = QByteArray::fromHex("AA55AA55AA55AA55000000000001");
    QByteArray binaryTime = TimeUtils::getCurrentTimeAsBinary();
    QByteArray partFrame = dataPart + binaryTime + QByteArray::fromHex("010000000000000000000000") + QByteArray::fromHex("0700010000000000");
    quint32 calculatedCrc = CRC32Verifier::calculate(partFrame);
    QByteArray crcBytes;
    crcBytes.resize(4);
    qToBigEndian<quint32>(calculatedCrc, reinterpret_cast<uchar*>(crcBytes.data()));
    QByteArray fullFrame = partFrame + QByteArray::fromHex("0102030405060708") + crcBytes + QByteArray::fromHex("EEFFEEFF");
    emit sendTcpData(fullFrame);

}
#if 0
void DeviceInfo::onProtocolConnect()
{
   protocolItem->setText("true");
   ui->tableWidget->setItem(0,0,protocolItem);
}
void DeviceInfo::onProtocolDisConnect()
{
    protocolItem->setText("false");
    ui->tableWidget->setItem(0, 0, protocolItem);
}

void DeviceInfo::onDepthConnect()
{
    depthItem->setText("true");
    ui->tableWidget->setItem(0, 1, depthItem);
}
void DeviceInfo::onDepthDisConnect()
{
    depthItem->setText("false");
    ui->tableWidget->setItem(0, 1, depthItem);
}

void DeviceInfo::onIrConnect()
{
    irItem->setText("true");
    ui->tableWidget->setItem(0, 2, depthItem);
}

void DeviceInfo::onIrDisConnect()
{
    irItem->setText("false");
    ui->tableWidget->setItem(0, 2, depthItem);
}
#endif

void DeviceInfo::manageUploadTask(QFuture<bool> future, const QString& fileName)
{
    QFutureWatcher<bool>* watcher = new QFutureWatcher<bool>(this);
    watcher->setFuture(future);

    connect(watcher, &QFutureWatcher<bool>::finished, [this, watcher, fileName]() {
        bool success = watcher->result();
        ui->upgradeBtn->setEnabled(true);

        if (success) {
            // 文件上传成功
            QMessageBox::information(this, "成功", "文件上传完成！");
            //ui->statusLabel->setText("上传完成: " + fileName);
        }
        else {
            QMessageBox::critical(this, "失败", "文件上传失败");
            //ui->statusLabel->setText("上传失败: " + fileName);
        }

        watcher->deleteLater();
    });


}

QFuture<bool> DeviceInfo::checkFileAsync(const QString& filePath)
{
    return QtConcurrent::run([filePath]() {
        QFile file(filePath);
        if (!file.exists()) {
            qDebug() << "文件不存在:" << filePath;
            return false;
        }

        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "无法打开文件:" << filePath;
            return false;
        }

        bool isEmpty = file.size() == 0;
        file.close();
        return !isEmpty; // 返回true表示文件不为空
        });
}

